package com.gdut.simple.data.remote.http.service.impl;

import com.gdut.simple.common.RequestCallback;
import com.gdut.simple.data.entity.Gank;
import com.gdut.simple.data.entity.Result;
import com.gdut.simple.data.remote.api.GankApi;
import com.gdut.simple.data.remote.http.service.IGankService;
import com.gdut.simple.data.remote.http.core.ServiceFactory;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class GankApiService {

    public static void getGankList(String type, int num, int page, final RequestCallback<List<Gank>> callback) {
        ServiceFactory.createService(GankApi.BASE_URL, IGankService.class)
                .getGankList(type, num, page)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorReturn(new Func1<Throwable, Result<List<Gank>>>() {
                    @Override
                    public Result<List<Gank>> call(Throwable throwable) {
                        if (callback != null) {
                            callback.onFailure(throwable.getMessage());
                        }
                        return null;
                    }
                })
                .map(new Func1<Result<List<Gank>>, List<Gank>>() {
                    @Override
                    public List<Gank> call(Result<List<Gank>> listResult) {
                        if (listResult != null) {
                            return listResult.getResult();
                        }
                        return null;
                    }
                })
                .subscribe(new Action1<List<Gank>>() {
                    @Override
                    public void call(List<Gank> ganks) {
                        if (ganks != null) {
                            if (callback != null) {
                                callback.onSuccess(ganks);
                            }
                        } else {
                            if (callback != null) {
                                callback.onFailure("null");
                            }
                        }
                    }
                });
    }

}
